import React, { useImperativeHandle } from 'react';
import { Form, Input, Card, DatePicker, Radio, Divider, Select, Avatar, Row, Col } from 'antd';
import moment from 'moment';
import isEmpty from 'lodash/isEmpty';
import { get as getPath } from 'object-path';
import { connect } from 'umi';
import TagNames from '@/components/Custom/TagNames';
import { SelectForm, PhoneForm, FormContainer, TreeSelectForm } from '@/components/UserForm';
import CascaderLoad from '@/components/CascaderLoad';
import { getDepartmentTree, getRoleList } from '@/services/components/userform';
import { getPostListByCondition } from '@/services/flowMine/apply';

// import { getType } from '@/utils/utils';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import useTreeSelectData from '@/hooks/useTreeSelectData';
import useUploadAvatar from '@/hooks/useUploadAvatar';

import UploadOss from '@/components/UploadOss';
import { dictionaryList } from '@/services/dictionary';

import styles from './index.less';
import AddForm from './addForm';

const { TextArea } = Input;
const { Option } = Select;

// const innerStyles = {
//     headStyle: {
//         border: 'initial',
//         fontSize: '16px',
//         fontWeight: 600
//     },
//     bodyStyle: {
//         padding: '10px'
//     },
//     orgEditInfoTitle: {
//         fontSize: 16,
//         fontWeight: 600,
//         color: '#000',
//         margin: '2px 0 24px 0'
//     }
// };
// const getInt = int => {
//     if (int === -1 || int === '') {
//         return undefined;
//     }
//     return int;
// };
const getCompanyId = ({ userCode, formData, treeNode, isTreeNode }) => {
    if (userCode) {
        return formData.companyId;
    }
    if (isTreeNode) {
        return treeNode.companyId;
    }
    return null;
};
const getDepartmentId = ({ userCode, formData }) => {
    if (userCode) {
        return formData.departmentId;
    }
    return null;
};

/**
 * 新增编辑员工
 * @param {*} props
 */
const AddEmployee = props => {
    const {
        form,
        form: { getFieldDecorator },
        userCode,
        treeNode = {},
        formData = {},
        dictionary,
        dictionary: { agreeType = [], sexType = [], household = [] },
        // setPostTypeRemark,
        setObaCompanyId,
        setCompanyName,
        children,
        // postTypeRemark,
        obaCompanyId,
        // localCompanyId,
        isDisabled,
        dispatch,
        childRef
    } = props;

    const [companyTreeData, companyTreeLoading] = useTreeSelectData('company');
    const { onFileChange, avatarData, existAvatar, updateAvatar } = useUploadAvatar({
        dispatch,
        user: { id: formData.id, orgUserId: formData.orgUserId, avatarFile: formData.avatarFile }
    });

    useImperativeHandle(childRef, () => ({
        updateAvatar
    }));
    const [fileList, setFileList] = React.useState([]);
    const [selectId, setSelectId] = React.useState('');
    const [isChina, setIsChina] = React.useState(false); // 用于户籍类型判断必填
    const [selectDepartmentId, setSelectDepartmentId] = React.useState('');
    const [postList, setPostList] = React.useState([]);
    const [curGradeDesc, setCurGradeDesc] = React.useState('');
    const [curPostDescription, setCurPostDescription] = React.useState('');
    const [curPostGradeDimensions, setCurPostGradeDimensions] = React.useState([]);
    // 获得户籍类型remark
    const getSelectId = value => {
        household.map(item => {
            if (value === item.dictValue) {
                setSelectId(item.id);
            }
            return '';
        });
        form.setFieldsValue({
            secondHouseholdType: undefined
        });
    };
    /**
     * 职位下拉框发生变化重新请求职级下拉接口
     * 取职位上的`postTypeRemark`做dictCode 请求职级的字典
     */
    // const getRankList = (e, option) => {
    //     let res = '';
    //     if (getType(option) === 'array') {
    //         res = getPath(option, '0.props.posttyperemark', '');
    //     } else if (getType(option) === 'object') {
    //         res = getPath(option, 'props.posttyperemark', '');
    //     }
    //     form.setFieldsValue({
    //         employeeRank: undefined
    //     });
    //     setPostTypeRemark('employeeLevelType');
    // };
    /**
     * 切换公司时 联动操作
     * @param {*} value
     * @param {*} label
     */
    const companyChange = (value, label) => {
        setObaCompanyId(value);
        setCompanyName(label[0]);
        form.setFieldsValue({
            employeeRank: undefined,
            departmentId: null,
            postId: undefined,
            roles: []
        });
    };
    const isTreeNode = !!(treeNode && treeNode.id);
    const returnNationalArea = data => {
        if (data === '') {
            return [];
        }
        return data.split(',');
    };
    const changeNationalArea = e => {
        // 如果籍贯存在中国则作判断
        if (e[0] === '中国') {
            setIsChina(true);
        } else {
            setIsChina(false);
        }
    };
    // 取出必填参数
    const returenRequired = [
        {
            required: true,
            message: '请选择'
        }
    ];

    // 获取职级
    const getEmployeeRankName = value => {
        const curList = postList.find(item => item.id === value);
        form.setFieldsValue({
            employeeRank: curList.postGradeCode
        });
        setCurGradeDesc(curList.gradeDesc);
        setCurPostDescription(curList.postDescription);
        setCurPostGradeDimensions(curList.postGradeDimensions);
    };
    // 职级定义维度
    const renderPostGradeDimensions = () =>
        curPostGradeDimensions &&
        curPostGradeDimensions.length > 0 &&
        curPostGradeDimensions.map(item => (
            <span className={styles.dimensionItem}>
                <span className={styles.dimensionName}>{`· ${item.dimensionName}：`}</span>
                <span>{item.demand}</span>
                <br />
            </span>
        ));
    React.useEffect(() => {
        if (formData && formData.departmentId) {
            setSelectDepartmentId(formData.departmentId);
            setCurGradeDesc(formData.gradeDesc);
            setCurPostDescription(formData.postDescription);
            setCurPostGradeDimensions(formData.postGradeDimensions);
        }
    }, [formData]);
    return (
        <Card bordered={false} className={styles.fixCard}>
            <div className={styles.orgEditInfoTitle}>基础信息</div>
            <div className={styles.addFormListWrap}>
                <FormContainer>
                    <Form.Item label="用户名">
                        {getFieldDecorator('userName', {
                            initialValue: userCode ? formData.userName : '',
                            rules: [
                                {
                                    required: true,
                                    message: '用户名不能为空'
                                },
                                {
                                    pattern: /^[a-zA-Z,_-\s]{1,}$/,
                                    message: '只限定输入英文字符'
                                },
                                {
                                    min: 2,
                                    max: 50,
                                    message: '用户名字数范围:2到50个字符'
                                }
                            ]
                        })(<Input placeholder="请输入用户名" disabled={isDisabled} />)}
                    </Form.Item>
                    {userCode && (
                        <Form.Item label="员工工号">
                            {getFieldDecorator('userNo', {
                                initialValue: formData.userNo,
                                rules: [
                                    {
                                        required: true,
                                        message: '员工工号不能为空'
                                    },
                                    {
                                        pattern: /^[a-zA-Z0-9]+$/
                                    },
                                    {
                                        min: 1,
                                        max: 15
                                    }
                                ]
                            })(<Input placeholder="请输入工号" disabled={!!userCode} />)}
                        </Form.Item>
                    )}
                    <Form.Item label="员工姓名">
                        {getFieldDecorator('employeeName', {
                            initialValue: userCode ? formData.employeeName : '',
                            rules: [
                                {
                                    required: true,
                                    message: '员工姓名不能为空'
                                },
                                // {
                                //     pattern: /^[\u4e00-\u9fa5a-zA-Z,_-\s]{1,}$/,
                                //     message: '只限定输入中英文'
                                // },
                                {
                                    min: 2,
                                    max: 50,
                                    message: '员工姓名字数范围:2到50个字符'
                                }
                            ]
                        })(<Input placeholder="输入员工真实姓名" disabled={isDisabled} />)}
                    </Form.Item>
                    <Form.Item label="注册邮箱">
                        {getFieldDecorator('email', {
                            initialValue: userCode ? formData.email : '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入注册邮箱地址'
                                },
                                {
                                    pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
                                    message: '邮件格式不正确'
                                }
                            ]
                        })(<Input placeholder="请输入注册邮箱地址" disabled={!!userCode} />)}
                    </Form.Item>
                    {/* 手机号码 区号目前由前端写死 */}
                    <Form.Item label="手机号">
                        {getFieldDecorator('mobile', {
                            initialValue: {
                                areaCode: userCode ? formData.areaCode : null,
                                mobile: userCode ? formData.mobile : null
                            },
                            rules: [
                                {
                                    required: true,
                                    validator(rule, value, callback) {
                                        const regex = /^\d{7,11}$/;
                                        const { areaCode, mobile } = value;
                                        if (!areaCode) {
                                            callback('区号不能为空');
                                        } else if (!mobile) {
                                            callback('手机号不能为空');
                                        } else if (!regex.test(mobile)) {
                                            callback('只能输入7-11位数字');
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })(
                            <PhoneForm
                                inputProps={{
                                    placeholder: '请填写手机号',
                                    disabled: isDisabled
                                }}
                                selectProps={{
                                    placeholder: '区号',
                                    disabled: isDisabled
                                }}
                            />
                        )}
                    </Form.Item>

                    <Form.Item label="性别">
                        {getFieldDecorator('sex', {
                            initialValue: userCode ? formData.sex : null,
                            rules: [
                                {
                                    required: true,
                                    message: '性别不能为空'
                                }
                            ]
                        })(
                            <Radio.Group disabled={isDisabled}>
                                {sexType.map(item => (
                                    <Radio value={item.dictValue} key={item.dictValue}>
                                        {item.dictName}
                                    </Radio>
                                ))}
                            </Radio.Group>
                        )}
                    </Form.Item>
                    <Form.Item label="籍贯/国籍">
                        {getFieldDecorator('nationalArea', {
                            initialValue: userCode ? returnNationalArea(getPath(formData, 'nationalArea', '')) : []
                        })(
                            <CascaderLoad
                                cascaderProps={{
                                    placeholder: '请选择籍贯/国籍',
                                    disabled: isDisabled
                                }}
                                onChange={changeNationalArea}
                                // asianData={asian}
                            />
                        )}
                    </Form.Item>
                    {/* 户籍类型 */}
                    {isChina ? (
                        <Form.Item label="户籍类型" required={isChina} style={{ marginBottom: 0 }}>
                            <Row gutter={15}>
                                <Col md={12} xs={24} sm={24}>
                                    <Form.Item>
                                        {getFieldDecorator('firstHouseholdType', {
                                            initialValue: formData.firstHouseholdType || undefined,
                                            rules: isChina ? returenRequired : []
                                        })(
                                            <Select placeholder="请选择" onChange={getSelectId} allowClear>
                                                {household &&
                                                    household.map(item => (
                                                        <Option value={item.dictValue} key={item.dictValue}>
                                                            {item.dictName}
                                                        </Option>
                                                    ))}
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                                <Col md={12} xs={24} sm={24}>
                                    <Form.Item>
                                        {getFieldDecorator('secondHouseholdType', {
                                            initialValue: formData.secondHouseholdType || undefined,
                                            rules: isChina ? returenRequired : []
                                        })(
                                            <SelectForm
                                                params={{
                                                    parentId: selectId
                                                }}
                                                requireParam={['parentId']}
                                                getData={params =>
                                                    dictionaryList(params).then(res => {
                                                        if (res && res.code === 10000 && res.data) {
                                                            return res.data || [];
                                                        }
                                                        return [];
                                                    })
                                                }
                                                fieldsName={{
                                                    selectValue: 'dictValue',
                                                    selectTitle: 'dictName'
                                                }}
                                                selectProps={{
                                                    placeholder: '请选择',
                                                    allowClear: true
                                                }}
                                            />
                                        )}
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form.Item>
                    ) : null}
                    <Form.Item label="出生日期">
                        {getFieldDecorator('birthday', {
                            initialValue: userCode && !isEmpty(formData.birthday) ? moment(formData.birthday) : null
                        })(<DatePicker style={{ width: '100%' }} placeholder="请选择出生日期" disabled={isDisabled} />)}
                    </Form.Item>

                    <Form.Item label="居住地址">
                        {getFieldDecorator('address', {
                            initialValue: userCode ? returnNationalArea(getPath(formData, 'address', '')) : []
                        })(
                            <CascaderLoad
                                cascaderProps={{
                                    placeholder: '请选择居住地址',
                                    disabled: isDisabled
                                }}
                                // asianData={asian}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="最高学历">
                        {getFieldDecorator('highestDegree', {
                            initialValue: userCode ? formData.highestDegree : undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '最高学历不能为空'
                                }
                            ]
                        })(
                            <Select placeholder="请选择最高学历" disabled={isDisabled}>
                                {agreeType.map(item => (
                                    <Option value={item.dictValue} key={item.dictValue}>
                                        {item.dictName}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label=" " colon={false} style={{ marginTop: '-20px' }}>
                        {getFieldDecorator('detailAddress', {
                            initialValue: userCode ? formData.detailAddress : null
                        })(<Input.TextArea rows={3} placeholder="请输入详细居住地址" disabled={isDisabled} />)}
                    </Form.Item>
                    {userCode ? (
                        <Form.Item label="上传图片" vvspan={24} labelCol={{ md: 4 }} wrapperCol={{ md: 20 }}>
                            <div className={styles.upload}>
                                <UploadOss
                                    disabled={isDisabled}
                                    dragAble={false}
                                    uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                                    checkFileSize={3}
                                    checkFileSizeMsg="图片不能大于3M！"
                                    sysCode="OA"
                                    setFileList={(file, uploadResourceResult) => {
                                        setFileList(file);
                                        onFileChange(file, uploadResourceResult);
                                    }}
                                    fileList={fileList}
                                    businessCode="SysAvatar"
                                    categoryCode="avatarFile"
                                    isSingle
                                    checkFileType="JPG,JPEG,BMP,GIF,PNG"
                                    checkFileTypeMsg="只能上传JPG,JPEG,BMP,GIF,PNG格式的文件！"
                                >
                                    <Avatar
                                        icon={avatarData.loading ? 'loading' : 'user'}
                                        src={avatarData.url ? avatarData.url : existAvatar}
                                        size={104}
                                        style={{ flex: '0 0 80px' }}
                                    />
                                    <div className={styles.text}>修改头像</div>
                                </UploadOss>
                            </div>
                            <div className={styles.uploadTips}>请上传您的2寸白底近半年内照片</div>
                        </Form.Item>
                    ) : null}
                </FormContainer>
            </div>
            <Divider style={{ margin: '32px 0' }} />
            <div className={styles.orgEditInfoTitle}>部门职位角色</div>
            <div className={styles.addFormListWrap}>
                <FormContainer>
                    <Form.Item label="所属公司">
                        {getFieldDecorator('companyId', {
                            initialValue: getCompanyId({ userCode, formData, treeNode, isTreeNode }),
                            rules: [
                                {
                                    required: true,
                                    message: '所属公司不能为空'
                                }
                            ]
                        })(
                            // <TreeSelectForm
                            //     params={{ companyId: localCompanyId }}
                            //     requireParam={['companyId']}
                            //     getData={params =>
                            //         getCompanyTree(params).then(res => {
                            //             if (res && res.code === 10000 && res.data) {
                            //                 return res.data || [];
                            //             }
                            //             return [];
                            //         })
                            //     }
                            //     fieldsName={{
                            //         value: 'id',
                            //         title: 'companyName'
                            //     }}
                            //     onChange={companyChange}
                            //     Props={{
                            //         disabled: isTreeNode || isDisabled,
                            //         placeholder: '请选择所属公司',
                            //         style: { width: '100%' },
                            //         showArrow: true
                            //     }}
                            // />
                            <TreeSelectPro
                                disabled={isTreeNode || isDisabled || userCode !== undefined}
                                loading={companyTreeLoading}
                                showSearch
                                allowClear
                                treeDefaultExpandAll
                                treeData={companyTreeData}
                                onChange={companyChange}
                            />
                        )}
                    </Form.Item>
                    {/* 编辑员工时： 取当前员工所属公司id获取部门列表 */}
                    <Form.Item label="部门">
                        {getFieldDecorator('departmentId', {
                            initialValue: getDepartmentId({ userCode, formData })
                        })(
                            <TreeSelectForm
                                params={{
                                    companyId: obaCompanyId
                                }}
                                defaultExpand="department"
                                requireParam={['companyId']}
                                getData={params =>
                                    getDepartmentTree(params).then(res => {
                                        if (res && res.code === 10000 && res.data) {
                                            return res.data || [];
                                        }
                                        return [];
                                    })
                                }
                                fieldsName={{
                                    value: 'id',
                                    title: 'departmentName'
                                }}
                                Props={{
                                    placeholder: '请选择所属部门',
                                    showArrow: true,
                                    disabled: isDisabled || userCode !== undefined
                                }}
                                onChange={v => {
                                    setSelectDepartmentId(v);
                                    setCurGradeDesc('');
                                    setCurPostDescription('');
                                    form.setFieldsValue({
                                        postId: undefined,
                                        employeeRank: undefined
                                    });
                                }}
                            />
                        )}
                    </Form.Item>

                    <Form.Item label="角色">
                        {getFieldDecorator('roles', {
                            initialValue: userCode ? formData.roleIds : [],
                            rules: [
                                {
                                    required: true,
                                    message: '角色不能为空'
                                }
                            ]
                        })(
                            <SelectForm
                                params={{
                                    companyId: obaCompanyId
                                }}
                                requireParam={['companyId']}
                                getData={params =>
                                    getRoleList(params).then(res => {
                                        if (res && res.code === 10000 && res.data) {
                                            return res.data || [];
                                        }
                                        return [];
                                    })
                                }
                                fieldsName={{
                                    selectValue: 'id',
                                    selectTitle: 'roleName'
                                }}
                                selectProps={{
                                    mode: 'multiple',
                                    placeholder: '请选择角色',
                                    disabled: isDisabled
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="入职时间">
                        {getFieldDecorator('timeOfEntry', {
                            initialValue: userCode ? moment(formData.timeOfEntry) : null,
                            rules: [
                                {
                                    required: true,
                                    message: '入职时间不能为空'
                                }
                            ]
                        })(<DatePicker style={{ width: '100%' }} disabled={isDisabled} />)}
                    </Form.Item>
                    <Form.Item label="职位">
                        {getFieldDecorator('postId', {
                            initialValue: userCode ? formData.postId : undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '职位不能为空'
                                }
                            ]
                        })(
                            <SelectForm
                                params={{
                                    departmentId: selectDepartmentId
                                }}
                                getData={params => {
                                    if ((formData && formData.departmentId) || selectDepartmentId === '') {
                                        return getPostListByCondition(params).then(res => {
                                            if (res && res.code === 10000 && res.data) {
                                                setPostList(res.data);
                                                return res.data || [];
                                            }
                                            return [];
                                        });
                                    }
                                    if (userCode === undefined) {
                                        return getPostListByCondition(params).then(res => {
                                            if (res && res.code === 10000 && res.data) {
                                                setPostList(res.data);
                                                return res.data || [];
                                            }
                                            return [];
                                        });
                                    }
                                    return [];
                                }}
                                fieldsName={{
                                    selectValue: 'id',
                                    selectTitle: 'postName'
                                }}
                                selectProps={{
                                    placeholder: '请选择职位',
                                    disabled: isDisabled || userCode !== undefined
                                }}
                                onChange={getEmployeeRankName}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="职级">
                        {getFieldDecorator('employeeRank', {
                            initialValue: formData.postGradeCode
                        })(<Input placeholder="请输入员工入职职级" disabled />)}
                    </Form.Item>
                    {curPostDescription ? (
                        <Form.Item label="职责描述" vvspan={24} labelCol={{ md: 4 }} wrapperCol={{ md: 20 }}>
                            <TextArea value={curPostDescription} rows={3} disabled />
                        </Form.Item>
                    ) : null}
                    {curGradeDesc ? (
                        <Form.Item label="职级定义" vvspan={24} labelCol={{ md: 4 }} wrapperCol={{ md: 20 }}>
                            <div className={styles.feignTextarea}>
                                <div
                                    style={{ marginBottom: 5 }}
                                    dangerouslySetInnerHTML={{
                                        __html: curGradeDesc && curGradeDesc.replace(/(\r\n|\n|\r)/gm, '<br />')
                                    }}
                                />
                                {renderPostGradeDimensions()}
                            </div>
                        </Form.Item>
                    ) : null}
                    <Form.Item label="职责标签">
                        {getFieldDecorator('jobLabel', {
                            initialValue: userCode ? getPath(formData, 'jobLabel', []) : []
                        })(
                            <TagNames
                                maxLength={5}
                                disabled={isDisabled}
                                onErr={value => {
                                    form.setFields({
                                        jobLabel: {
                                            value,
                                            errors: [new Error('请输入2-50个字符,并且不能重复')]
                                        }
                                    });
                                }}
                                onSucc={value => {
                                    form.setFields({
                                        jobLabel: {
                                            value,
                                            errors: []
                                        }
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                </FormContainer>
            </div>
            {/* <Divider style={{ margin: '32px 0' }} /> */}
            {/* <div className={styles.orgEditInfoTitle}>学历证书</div>
            <Form.Item label="最高学历">
                {getFieldDecorator('highestDegree', {
                    initialValue: userCode ? formData.highestDegree : null,
                    rules: [
                        {
                            required: true,
                            message: '最高学历不能为空'
                        }
                    ]
                })(
                    <Radio.Group disabled={isDisabled}>
                        {agreeType.map(item => (
                            <Radio value={item.dictValue} key={item.dictValue}>
                                {item.dictName}
                            </Radio>
                        ))}
                    </Radio.Group>
                )}
            </Form.Item>
            <Form.Item label="毕业院校">
                {getFieldDecorator('graduateSchool', {
                    rules: [
                        {
                            min: 1,
                            max: 50,
                            message: '1--50个字符'
                        }
                    ],
                    initialValue: userCode ? formData.graduateSchool : null
                })(<Input placeholder="请输入毕业学校" disabled={isDisabled} />)}
            </Form.Item>
            <Form.Item label="专业">
                {getFieldDecorator('major', {
                    rules: [
                        {
                            min: 1,
                            max: 50,
                            message: '1--50个字符'
                        }
                    ],
                    initialValue: userCode ? formData.major : ''
                })(<Input placeholder="请输入所学专业名称" disabled={isDisabled} />)}
            </Form.Item>
            <Form.Item label="职称证书">
                {getFieldDecorator('certificate', {
                    rules: [
                        {
                            min: 1,
                            max: 50,
                            message: '1--50个字符'
                        }
                    ],
                    initialValue: userCode ? formData.certificate : null
                })(<Input placeholder="请输入证书名称" disabled={isDisabled}/>)}
            </Form.Item> */}
            {userCode ? (
                <AddForm
                    form={form}
                    user={formData}
                    dict={dictionary}
                    userCode={userCode}
                    formData={formData}
                    isDisabled={isDisabled}
                />
            ) : null}
            {children}
        </Card>
    );
};
export default connect(({ loading, user }) => ({
    loading,
    user,
    avatarFile: user.avatarFile
}))(AddEmployee);
